# !/usr/bin python3                                 
# encoding: utf-8 -*-                            
# @author: 沙陌 微信：Matongxue_2
# @Time: 2021/11/4 13:25
# @Copyright：北京码同学
import sys

import jsonpath
import requests

session = requests.session()


class WxNotice:

    def __init__(self, url, job_name, build_number, result, user, build_url):
        self.url = url
        self.method = 'post'
        self.json = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"#### {job_name}测试完成  \n - 任务：第{build_number}次\n - 状态：{result} \n - 执行人: {user}  \n \n[查看报告]({build_url}/allure) "
            }
        }

    def send(self):
        resp = session.request(method=self.method, url=self.url, json=self.json)
        return resp


class JenkinsStutus:
    # http://localhost:8080/job/liushuixian/11/api/json
    def __init__(self, build_url, username, password):
        self.url = f'{build_url}/api/json'
        self.method = 'get'
        session.auth = (username, password)

    def send(self):
        resp = session.request(method=self.method, url=self.url)
        return resp


if __name__ == '__main__':
    # WxNotice().send()
    agrs = sys.argv
    build_url = agrs[1]
    username = agrs[2]
    password = agrs[3]
    wx_url = agrs[4]
    job_name = agrs[5]
    build_number = agrs[6]
    # url = 'http://localhost:8080/job/liushuixian/11/api/json'
    # 调用任务执行数据
    jenkins_result = JenkinsStutus(build_url, username, password)
    resp = jenkins_result.send()
    # 获取任务执行人
    user = jsonpath.jsonpath(resp.json(), '$..userName')[0]
    # 获取任务执行结果
    result = jsonpath.jsonpath(resp.json(), '$.result')[0]
    print(user, result)

    # wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d17d0f68-0859-4022-a7a1-b5fa480f5f29'
    WxNotice(wx_url, job_name, build_number, result, user, build_url).send()
